package param_model

import (
	"errors"
	"fmt"
	"regexp"
	"strings"
)

type Trade struct {
	MerchantId  int     `form:"pay_memberid"`
	BankCode    int     `form:"pay_bankcode"`
	Amount      float64 `form:"pay_amount"`
	Sign        string  `form:"pay_md5sign"`
	ProductName string  `form:"pay_productname"`
	NotifyUrl   string  `form:"pay_notifyurl"`
	CallbackUrl string  `form:"pay_callbackurl"`
	ApplyDate   string  `form:"pay_applydate"`
	Attach      string  `form:"pay_attach"`
	OrderId     string  `form:"pay_orderid"`

	memberId  int
	channelId int
}

func (t *Trade) SetMemberId(id int) {
	t.memberId = id
}

func (t *Trade) GetMemberId() int {
	return t.memberId
}

func (t *Trade) SetChannelId(id int) {
	t.channelId = id
}

func (t *Trade) GetChannelId() int {
	return t.channelId
}

func (t *Trade) Validate() error {
	t.NotifyUrl = strings.TrimSpace(t.NotifyUrl)
	t.CallbackUrl = strings.TrimSpace(t.CallbackUrl)
	t.ApplyDate = strings.TrimSpace(t.ApplyDate)
	t.Attach = strings.TrimSpace(t.Attach)
	t.OrderId = strings.TrimSpace(t.OrderId)
	t.Sign = strings.TrimSpace(t.Sign)
	t.ProductName = strings.TrimSpace(t.ProductName)

	if m, _ := regexp.MatchString(`^1\d{4}$`, fmt.Sprintf("%d", t.MerchantId)); !m {
		return errors.New("商户号(pay_memberid)不正确!")
	}
	if m, _ := regexp.MatchString(`^\d{3}$`, fmt.Sprintf("%d", t.BankCode)); !m {
		return errors.New("通道编码(pay_bankcode)不正确!")
	}

	if m, _ := regexp.MatchString(`^\d*\.?\d{0,2}$`, fmt.Sprint(t.Amount)); !m {
		return errors.New("金额(pay_amount)不正确,金额最多两位数小数!")
	}

	//todo 判断同步地址和异步通知地址格式

	if len(t.ApplyDate) == 0 {
		return errors.New("提交时间(pay_applydate)不正确!")
	}
	if m, _ := regexp.MatchString(`^\w{6,50}$`, t.OrderId); !m {
		return errors.New("商户订单号(pay_orderid)格式不正确!")
	}
	if m, _ := regexp.MatchString(`\w{32}$`, t.Sign); !m {
		return errors.New("签名参数(pay_md5sign)不正确!")
	}

	productNameMatch := regexp.MustCompile(`^[\x{4e00}-\x{9fa5}a-zA-Z0-9\_\-]+$`)
	if !productNameMatch.MatchString(t.ProductName) {
		return errors.New("商品名称(pay_productname)格式不正确")
	}

	if len(t.Attach) > 0 {
		attachMatch := regexp.MustCompile(`^[\x{4e00}-\x{9fa5}a-zA-Z0-9\_\-\|\=]+$`)
		if !attachMatch.MatchString(t.Attach) {
			return errors.New("附加信息(pay_attach)格式不正确!")
		}
	}

	//设置商户的用户ID
	t.SetMemberId(t.MerchantId - 10000)
	return nil
}
